package com.bdqn.util;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 字符集编码过滤器
 */
@WebFilter(urlPatterns = {"/*"})
public class CharacterFilter implements Filter {
    @Override
    //init:过滤器的初始化方法，过滤器加载的时候调用一次
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    //doFilter：过滤器的过滤方法，正式代码
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.先将ServletRequest和ServletResponse转为我们熟悉的Httpxxxx
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //2.获取请求方式
        String method = req.getMethod();
        //3.如果是post请求就做中文转码处理
        //xxxIgnoreCase()忽略字母大小写
        if (method.equalsIgnoreCase("post")){
            req.setCharacterEncoding("utf-8");
        }
        //4.继续执行【放过请求】
        filterChain.doFilter(req,resp);
    }

    @Override
    //destroy：过滤器的销毁方法
    public void destroy() {

    }
}
